<template>
  <div class="user-info-container">
    <h2 class="title">用户信息管理</h2>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter">
      <el-input
        v-model="searchQuery"
        placeholder="请输入用户ID/姓名/手机号搜索"
        class="search-input"
        clearable
        @clear="handleSearchClear"
      >
        <template #append>
          <el-button :icon="Search" @click="handleSearch" />
        </template>
      </el-input>

      <el-select
        v-model="filterStatus"
        placeholder="用户状态"
        clearable
        class="status-filter"
        @change="handleFilterChange"
      >
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <el-button type="primary" @click="showAddDialog" class="add-btn">
        添加新用户
      </el-button>
    </div>

    <!-- 用户信息表格 -->
    <el-table
      :data="filteredUsers"
      border
      style="width: 100%"
      v-loading="loading"
      @sort-change="handleSortChange"
    >
      <el-table-column prop="id" label="用户ID" width="100" sortable />
      <el-table-column prop="avatar" label="头像" width="100">
        <template #default="{ row }">
          <el-avatar :size="50" :src="row.avatar || avatar" />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="realName" label="真实姓名" width="120" />
      <el-table-column prop="phone" label="手机号" width="150" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="address" label="地址" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
            {{ statusMap[row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="注册时间"
        width="180"
        sortable
      />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            :type="row.status === 'active' ? 'danger' : 'success'"
            @click="handleToggleStatus(row)"
          >
            {{ row.status === "active" ? "禁用" : "启用" }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalUsers"
        layout="total, sizes, prev, pager, next, jumper"
        :pager-count="5"
        :small="false"
        :background="true"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      >
        <template #total="{ total }">
          <span>共 {{ total }} 条记录</span>
        </template>
        <template #sizes="{ sizes }">
          <span>每页显示 {{ sizes.join("/") }} 条</span>
        </template>
        <template #prev>
          <el-button type="text">上一页</el-button>
        </template>
        <template #next>
          <el-button type="text">下一页</el-button>
        </template>
        <template #jumper>
          <div class="jumper-container">
            <span>跳至</span>
            <el-input-number
              v-model="currentPage"
              :min="1"
              :max="Math.ceil(totalUsers / pageSize)"
              controls-position="right"
              size="small"
            />
            <span>页</span>
          </div>
        </template>
      </el-pagination>
    </div>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="50%"
      @closed="resetForm"
    >
      <el-form
        ref="userForm"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="formData.realName" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="用户状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { Search, Plus } from "@element-plus/icons-vue";
import avatar from "@/assets/avatar.png";

// 用户数据
const users = ref([]);
const loading = ref(false);
const searchQuery = ref("");
const filterStatus = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const totalUsers = ref(0);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("添加用户");
const formData = ref({
  id: "",
  username: "",
  realName: "",
  phone: "",
  email: "",
  address: "",
  status: "active",
  avatar: "",
});
const userForm = ref(null);

// 状态选项
const statusOptions = [
  { value: "active", label: "启用" },
  { value: "inactive", label: "禁用" },
];

const statusMap = {
  active: "启用",
  inactive: "禁用",
};

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  realName: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择用户状态", trigger: "change" }],
};

// 计算属性 - 过滤后的用户列表
// 计算属性 - 过滤后的用户列表(添加分页逻辑)
const filteredUsers = computed(() => {
  let result = users.value;

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter((user) => {
      return (
        user.id.toString().includes(query) ||
        user.username.toLowerCase().includes(query) ||
        user.realName.toLowerCase().includes(query) ||
        user.phone.includes(query)
      );
    });
  }

  // 状态过滤
  if (filterStatus.value) {
    result = result.filter((user) => user.status === filterStatus.value);
  }

  // 更新总记录数
  totalUsers.value = result.length;
  
  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return result.slice(start, end);
});

// 生命周期钩子
onMounted(() => {
  fetchUsers();
});

// 获取用户数据
const fetchUsers = async () => {
  loading.value = true;
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 800));
    // 模拟数据 (reduced from 50 to 15 items)
    users.value = Array.from({ length: 15 }, (_, i) => ({
      id: 1000 + i,
      username: `用户${i}`,
      realName: ["张", "李", "王", "赵", "刘"][i % 5] + "某",
      phone: `138${Math.floor(10000000 + Math.random() * 90000000)}`,
      email: `user${i}@qq.com`,
      address:
        ["北京市", "上海市", "广州市", "深圳市", "成都市"][i % 5] +
        "某区某街道" +
        (i + 1) +
        "号",
      status: Math.random() > 0.2 ? "active" : "inactive",
      createTime: new Date(
        Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000
      ).toLocaleString(),
      avatar: "", // 所有用户使用默认头像
    }));
    totalUsers.value = users.value.length;
  } catch (error) {
    console.error("获取用户数据失败:", error);
    ElMessage.error("获取用户数据失败");
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
};

const handleSearchClear = () => {
  searchQuery.value = "";
  currentPage.value = 1;
};

// 筛选处理
const handleFilterChange = () => {
  currentPage.value = 1;
};

// 排序处理
const handleSortChange = ({ column, prop, order }) => {
  console.log("排序:", prop, order);
  // 实际项目中这里应该调用API进行排序
};

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
};

const handlePageChange = (page) => {
  currentPage.value = page;
};

// 显示添加用户对话框
const showAddDialog = () => {
  dialogTitle.value = "添加用户";
  dialogVisible.value = true;
};

// 编辑用户
const handleEdit = (row) => {
  dialogTitle.value = "编辑用户";
  formData.value = { ...row };
  dialogVisible.value = true;
};

// 切换用户状态
const handleToggleStatus = async (row) => {
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 500));
    row.status = row.status === "active" ? "inactive" : "active";
    ElMessage.success(`用户已${row.status === "active" ? "启用" : "禁用"}`);
  } catch (error) {
    console.error("状态切换失败:", error);
    ElMessage.error("状态切换失败");
  }
};

// 头像上传处理
const handleAvatarSuccess = (response, file) => {
  formData.value.avatar = URL.createObjectURL(file.raw);
};

const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPGOrPNG) {
    ElMessage.error("上传头像图片只能是 JPG/PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }

  return isJPGOrPNG && isLt2M;
};

// 提交表单
const submitForm = async () => {
  try {
    await userForm.value.validate();

    // 模拟API调用
    loading.value = true;
    await new Promise((resolve) => setTimeout(resolve, 800));

    if (formData.value.id) {
      // 更新用户
      const index = users.value.findIndex((u) => u.id === formData.value.id);
      if (index !== -1) {
        users.value[index] = { ...formData.value };
      }
      ElMessage.success("用户信息更新成功");
    } else {
      // 添加用户
      const newUser = {
        ...formData.value,
        id: Math.max(...users.value.map((u) => u.id)) + 1,
        createTime: new Date().toLocaleString(),
      };
      users.value.unshift(newUser);
      totalUsers.value++;
      ElMessage.success("用户添加成功");
    }

    dialogVisible.value = false;
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  formData.value = {
    id: "",
    username: "",
    realName: "",
    phone: "",
    email: "",
    address: "",
    status: "active",
    avatar: "",
  };
  if (userForm.value) {
    userForm.value.resetFields();
  }
};
</script>

<style scoped>
.user-info-container {
  padding: 20px;
}

.title {
  margin-bottom: 20px;
  color: #333;
  font-size: 24px;
}

.search-filter {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.status-filter {
  width: 150px;
}

.add-btn {
  margin-left: auto;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.jumper-container {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-left: 10px;
}
</style>
